﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.Remoting;
using System.Diagnostics;
using System.Management;
using System.Xml;
using Table = FCNS.Data.Table;
using System.IO;
using System.Data;

namespace DoubleH.Utility.IO
{
    public class FileTools
    {
        /// <summary>
        /// 检查版本,版本号必须如下格式: x.x.x.x ,否则返回false , updateUrl 格式必须正确,否则返回 false
        /// </summary>
        /// <param name="newVer">如何是 .xml 结尾则下载更新信息文件然后分析版本号</param>
        /// <param name="oldVer"></param>
        /// <returns></returns>
        public static string CheckVerByAssembly(string newVer, string oldVer)
        {
            if (string.IsNullOrEmpty(newVer) || string.IsNullOrEmpty(oldVer))
                return null;

            string newVerOK = newVer;
            bool force = false;//是否强制更新
            if (newVer.EndsWith(".xml"))
            {
                try
                {
                    XmlDocument xml = new XmlDocument();
                    xml.Load(newVer);
                    newVerOK = xml.SelectSingleNode("Update/Ver").InnerText;
                }
                catch { return null; }
            }

            if (newVerOK == oldVer)
                return null;

            Configuration.DoubleHConfig.AppConfig.ForceUpdate = force;
            return newVerOK;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter">.jpg  .txt .rar</param>
        /// <returns></returns>
        public static string GetFile(bool isOpen, params string[] filter)
        {
            string file = string.Empty;
            if (isOpen)
            {
                using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog())
                {
                    ofd.Multiselect = false;
                    if (filter == null || filter.Length == 0)
                        ofd.Filter = "所有文件 (*.*)|*.*";
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in filter)
                            sb.Append("(*" + str + ")|*" + str + "|");

                        ofd.Filter = sb.Remove(sb.Length - 1, 1).ToString();
                    }
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        file = ofd.FileName;
                }
            }
            else
            {
                using (System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog())
                {
                    if (filter == null || filter.Length == 0)
                        sfd.Filter = "所有文件 (*.*)|*.*";
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in filter)
                            sb.Append("(*" + str + ")|*" + str + "|");

                        sfd.Filter = sb.Remove(sb.Length - 1, 1).ToString();
                    }
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        file = sfd.FileName;
                }
            }
            return file;
        }

        /// <summary>
        /// 返回文件的MD5值
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string GetFileMD5(string filePath)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHasValue;

            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            try
            {
                oFileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                //计算文件的MD5值
                arrbytHasValue = oMD5Hasher.ComputeHash(oFileStream);
                oFileStream.Close();
                strHashData = System.BitConverter.ToString(arrbytHasValue);
                //替换掉计算出MD5值中的"-"
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
                //MessageBox.Show(strHashData);

            }
            catch (Exception ex)
            {
                MessageWindow.Show(ex.Message);
            }

            return strResult;
        }

        public bool ShareFolder(string polderPath, string shareName, string description)
        {
            try
            {
                while (polderPath.EndsWith("\\"))
                    polderPath = polderPath.Remove(polderPath.Length - 1);

                // Create a ManagementClass object

                ManagementClass managementClass = new ManagementClass("Win32_Share");

                // Create ManagementBaseObjects for in and out parameters

                ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");

                ManagementBaseObject outParams;

                // 设置输入参数

                inParams["Description"] = description;

                inParams["Name"] = shareName;

                inParams["Path"] = polderPath;

                inParams["Type"] = 0x0; // Disk Drive

                //Another Type:

                // DISK_DRIVE = 0x0

                // PRINT_QUEUE = 0x1

                // DEVICE = 0x2

                // IPC = 0x3

                // DISK_DRIVE_ADMIN = 0x80000000

                // PRINT_QUEUE_ADMIN = 0x80000001

                // DEVICE_ADMIN = 0x80000002

                // IPC_ADMIN = 0x8000003

                //inParams["MaximumAllowed"] = int maxConnectionsNum;

                // Invoke the method on the ManagementClass object

                outParams = managementClass.InvokeMethod("Create", inParams, null);

                // Check to see if the method invocation was successful

                //if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                //    MessageWindow.Show("共享目录初始化失败");
                return true;
            }
            catch
            {
                MessageWindow.Show("共享目录初始化失败");
                return false;
            }
        }

        public FCNS.Data.Interface.IDataImport CreateInstance(string tableName)
        {
            try
            {
                ObjectHandle oh = Activator.CreateInstanceFrom(FCNS.Data.DbDefine.baseDir + "FCNS.Data.dll", "FCNS.Data.Table." + tableName);
                FCNS.Data.Interface.IDataImport import = (oh.Unwrap() as FCNS.Data.Interface.IDataImport);
                return import;
            }
            catch
            {
                MessageWindow.Show("缺乏构造函数");
                return null;
            }
        }



        ///// <summary>
        ///// 导出列表数据为 CSV 格式
        ///// </summary>
        ///// <param name="data"></param>
        ///// <param name="fileName"></param>
        //public void ExportDataToFile(IList data, string fileName)
        //{
        //    if (data == null)
        //        return;

        //    if (string.IsNullOrEmpty(fileName))
        //        fileName = GetFile(false, ".csv");

        //    if (string.IsNullOrEmpty(fileName))
        //        return;

        //    StringBuilder sb = new StringBuilder();
        //    List<System.Reflection.PropertyInfo> info = new List<System.Reflection.PropertyInfo>();
        //    foreach (System.Reflection.PropertyInfo i in data[0].GetType().GetProperties())
        //        info.Add(i);

        //    for (int i = 0; i < info.Count; i++)
        //        sb.Append(info[i].Name + ",");

        //    sb.Remove(sb.Length - 1, 1);
        //    sb.Append("\r\n");

        //    for (int i = 0; i < data.Count; i++)
        //    {
        //        object vr = data[i];
        //        for (int j = 0; j < info.Count; j++)
        //        {
        //            object obj = info[j].GetValue(vr, null);
        //            sb.Append((obj ?? "") + ",");
        //        }
        //        sb.Remove(sb.Length - 1, 1);
        //        sb.Append("\r\n");
        //    }

        //    System.IO.File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
        //    if (MessageWindow.Show("", fileName + " 导出成功,是否打开文件?", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
        //        System.Diagnostics.Process.Start(fileName);
        //}
        /// <summary>
        /// 将DataGrid内容倒出到csv文件中
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="fileName"></param>
        public void ExportDataGridToFile(UC.DataGridExt grid, string fileName)
        {
            if (grid == null)
                return;
            if (!grid.HasItems)
                return;

            IFileIO ifile =  GetFileFormat(false, fileName);
            if (ifile == null)
                return;

            ifile.ExportDataGridToFile(grid);
            if (MessageWindow.Show("", ifile.FileName + " 导出成功,是否打开文件?", System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
                System.Diagnostics.Process.Start(ifile.FileName);

        }

        public DataTable ImportFileToDataTable(string tableName, string fileName)
        {
            IFileIO ifile = GetFileFormat(true,fileName);
            if (ifile == null)
                return null;

            FCNS.Data.Interface.IDataImport import = CreateInstance(tableName);
            if (import == null)
            {
                MessageWindow.Show("当前项目不支持数据导入");
                return null;
            }
            else
            {
                return ifile.ImportFileToDataTable();
            }
        } 

        private IFileIO GetFileFormat(bool isOpen, string fileName)
        {
            IFileIO ifile = null;
            if (string.IsNullOrEmpty(fileName))
                fileName = GetFile(isOpen, ExcelTool.ExtName, CsvTool.ExtName,TxtTool.ExtName);
            if (string.IsNullOrEmpty(fileName))
                return ifile;

            switch (Path.GetExtension(fileName))
            {
                case CsvTool.ExtName: ifile = new CsvTool(); break;
                case ExcelTool.ExtName: ifile = new ExcelTool(); break;
                case TxtTool.ExtName: ifile = new TxtTool(); break;
            }
            Debug.Assert(ifile != null);
            ifile.FileName = fileName;
            return ifile;
        }
    }
}